import { queryPage, create, remove, update } from './service';
import { queryDictList } from '@/services/dict';
import { routerRedux } from 'dva/router';
import { DICT } from './enum';
import {message} from 'antd';

export default {
  namespace: 'account',

  state: {
    list: { data: [] },
    details: [],
    cond: {},
    dict: {}
  },

  effects: {
    *initCond(_, { put }) {
      yield put({ type: 'setCond', payload: {} });
      yield put({ type: 'queryPage' })
    },
    *updateCond({ payload }, { put }) {
      yield put({ type: 'setCond', payload });
      yield put({ type: 'queryPage' })
    },
    *queryPage({ payload = { pageNum: 1 } }, { call, put, select }) {
      const cond = yield select(state => state.account.cond);
      const params = { ...payload, ...cond };
      if (!params.pageSize) params.pageSize = 10;
      const { list = [], total } = yield call(queryPage, params);
      yield put({ type: 'queryDict', payload: {keyList: DICT} });
      yield put({ type: 'setPage', payload: { list, total: +total } })
    },
    *queryDict({ payload }, { call, put }) {
      const dict = yield call(queryDictList, payload);
      yield put({ type: 'setDict', payload: dict })
    },
    *create({ payload }, { call, put }) {
      const ans = yield call(create, payload);
      if (ans) {
        message.success(ans);
        yield put({ type: 'queryPage' });
      }
      yield put({ type: 'upload/init' })
    },
    *update({ payload }, { call, put }) {
      yield call(update, payload);
      yield put(routerRedux.push('/data/account'));
    },
    *init({ payload }, { put }) {
      yield put({ type: 'queryDict', payload: payload.dict });
    },
    *remove({ payload }, { call, put }) {
      yield call(remove, payload);
      yield put({ type: 'queryPage' })
    },
    *upload({ payload }, { select, put }) {

    }
  },

  reducers: {
    setCond(state, action) {
      return {
        ...state,
        cond: action.payload
      }
    },
    setPage(state, action) {
      return {
        ...state,
        list: {
          data: action.payload.list,
          dataCnt: action.payload.total
        }
      }
    },
    setDict(state, action) {
      return {
        ...state,
        dict: action.payload
      }
    },
    setDictList(state, action) {
      return {
        ...state,
        dictList: action.payload
      }
    },
    setUpload(state, action) {
      return {
        ...state,
        upload: action.payload
      }
    }
  }
}

